In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pprint import pprint
from sklearn.preprocessing import StandardScaler, Imputer
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
from scipy.stats import itemfreq
from mpl_toolkits.mplot3d import Axes3D
# magic word for producing visualizations in notebook
%matplotlib inline
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';')
azdias_df = azdias.copy()
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
features_info_df = feat_info.copy()
features_info_df.set_index('attribute', inplace=True)
features_info_df['columns'] = features_info_df.index
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
print(azdias_df.shape)
print(list(azdias_df.columns.values))
azdias_df.describe()
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand to convert to a code cell, useesc --> y.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
# Identify missing or unknown data values and convert them to NaNs.
def convert(string_list):
missing_values_dict = {}
conv = lambda x: x[1:-1].split(',')
res = conv(string_list)
for item in res:
if item.replace('-','').isnumeric():
missing_values_dict[int(item)] = np.nan
if item.isalpha():
missing_values_dict[str(item)] = np.nan
return missing_values_dict
print(features_info_df.head(3))
missing_values = features_info_df[['columns','missing_or_unknown']].copy()
missing_values = missing_values.query('missing_or_unknown !="[]"')
missing_values['missing_or_unknown'] = missing_values['missing_or_unknown'].apply(convert)
missing_dict = {x[0]: x[1] for x in missing_values.itertuples(index=False)}
#missing_dict
missing_dict
for key,value in missing_dict.items():
azdias_df[key].replace(value, inplace=True)
azdias_df.head(3)
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Perform an assessment of how much missing data there is in each column of the
# dataset.
azdias_df.isnull().sum(axis=1).hist(bins=30)
na_counts_per_column = azdias_df.isnull().sum(axis=0).to_frame()
na_counts_per_column = na_counts_per_column.T.apply(lambda x: x / azdias_df.shape[0])
# Investigate patterns in the amount of missing data in each column.
na_counts_per_column.T.plot(kind='bar', figsize=(20,10))
# remove the columns that holds 20% and more of missing data
missing_20 = [col for col in azdias_df.columns if (azdias_df[col].isnull().sum()/azdias.shape[0]) * 100 > 20]
print(missing_20)
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
for col in missing_20:
azdias_df.drop(col, axis=1, inplace=True)
na_counts_per_column_new = azdias_df.isnull().sum(axis=0).to_frame()
na_counts_per_column_new = na_counts_per_column_new.T.apply(lambda x: x / azdias_df.shape[0])
ax = na_counts_per_column_new.T.plot(kind='bar', figsize=(30,10))
for p in ax.patches:
ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
based on above graphs we could conclude the following
some columns has high coorelation such as KBA05 related columns and PLZ8 related columns, as the ratios of missing data in their related columns are the same
in total 6 columns have been removed as listed below
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# How much data is missing in each row of the dataset?
missing_in_row = azdias.isnull().sum(axis=1)
missing_in_row = missing_in_row[missing_in_row > 0]/(len(azdias_df.columns)) * 100
plt.hist(missing_in_row, bins=10, facecolor='g', alpha=0.75)
plt.xlabel('missing values(%)')
plt.ylabel('Counts')
plt.title('missing value counts in rows')
plt.grid(True)
plt.show()
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
missing_data_le_2 = azdias_df[azdias_df.isnull().sum(axis=1) < 2].reset_index(drop=True)
missing_data_gt_2 = azdias_df[azdias_df.isnull().sum(axis=1) >= 2].reset_index(drop=True)
print(missing_data_le_2.shape)
missing_data_gt_2.head(3)
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
row = 15
col = 2
fig, ax =plt.subplots(nrows=row, ncols=col, figsize = (20,30))
index = 0
if index < 15:
for i in range(row):
sns.countplot(x=missing_data_gt_2.columns[index],data=missing_data_gt_2, ax=ax[i][0])
sns.countplot(x=missing_data_le_2.columns[index],data=missing_data_le_2, ax=ax[i][1])
index = index + 1
ax[0][0].set_title('alot of NaNs / row')
ax[0][1].set_title('few NaNs / row')
fig.tight_layout()
fig.show()
Looking at avarages of missing data per row, it seems that most rows have around 5%. I set the threshold to 2 missing values in each row, knowing that we are going to loose a lot of data but the remaining data is cleaner
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
types={}
for col in missing_data_le_2.columns:
data_type = features_info_df.loc[col].type
if data_type not in types:
types[data_type] = 1
else:
types[data_type] += 1
print(types)
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
bin_list = []
multi_level_list = []
filtered_features = features_info_df.loc[missing_data_le_2.columns]
cat_variable = missing_data_le_2[filtered_features[filtered_features['type'] == 'categorical']['columns']]
cat_variable
for t in cat_variable:
if len(cat_variable[t].value_counts()) == 2 and (
set(cat_variable[t]) & set([0, 1]) == set([0, 1]) or
set(cat_variable[t]) & set([0.0, 1.0]) == set([0.0, 1.0])
):
bin_list.append(t)
else:
multi_level_list.append(t)
print(cat_variable.info())
print('-'*50)
pprint('Binary: {}'.format(bin_list))
print('')
pprint('multi-level: {}'.format(multi_level_list))
missing_data_le_2[['GREEN_AVANTGARDE','SOHO_KZ','ANREDE_KZ']].T
# Re-encode categorical variable(s) to be kept in the analysis.
# encode binary
df_with_dummies = pd.get_dummies( missing_data_le_2, columns = bin_list ,drop_first=True)
# drop multi-level
for col in multi_level_list:
df_with_dummies.drop(col, axis=1, inplace=True)
print(df_with_dummies.columns.tolist())
df_with_dummies.shape
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
first_var_dict = {
-1:{'period': np.nan, 'direction': np.nan},
0:{'period': np.nan, 'direction': np.nan},
1: {'period': 40, 'direction': 'EW'},
2: {'period': 40, 'direction': 'EW'},
3: {'period': 50, 'direction': 'EW'},
4: {'period': 50, 'direction': 'EW'},
5: {'period': 60, 'direction': 'EW'},
6: {'period': 60, 'direction': 'W'},
7: {'period': 60, 'direction': 'E'},
8: {'period': 70, 'direction': 'EW'},
9: {'period': 70, 'direction': 'EW'},
10: {'period': 80, 'direction': 'W'},
11: {'period': 80, 'direction': 'W'},
12: {'period': 80, 'direction': 'E'},
13: {'period': 80, 'direction': 'E'},
14: {'period': 90, 'direction': 'EW'},
15: {'period': 90, 'direction': 'EW'}
}
#initialize two columns
df_with_dummies['PRAEGENDE_JUGENDJAHRE_PERIOD']= 0
df_with_dummies['PRAEGENDE_JUGENDJAHRE_DIRECTION'] = 'x'
for key, values in first_var_dict.items():
#df_with_dummies[['PRAEGENDE_JUGENDJAHRE_PERIOD','PRAEGENDE_JUGENDJAHRE_DIRECTION']] =
row_indexes = df_with_dummies[df_with_dummies['PRAEGENDE_JUGENDJAHRE'] == key].index
df_with_dummies.loc[row_indexes,'PRAEGENDE_JUGENDJAHRE_PERIOD']= values['period']
df_with_dummies.loc[row_indexes,'PRAEGENDE_JUGENDJAHRE_DIRECTION']= values['direction']
# check missing
print(f'missing values for [PRAEGENDE_JUGENDJAHRE_PERIOD]: ', df_with_dummies[df_with_dummies['PRAEGENDE_JUGENDJAHRE_PERIOD'] == 0].shape[0])
print('missing values for [PRAEGENDE_JUGENDJAHRE_DIRECTION]: ', df_with_dummies[df_with_dummies['PRAEGENDE_JUGENDJAHRE_DIRECTION'] == 'x'].shape[0])
# drop the original column
df_with_dummies.drop(['PRAEGENDE_JUGENDJAHRE'], axis=1, inplace=True)
#create dummy for direction
df_with_dummies = pd.get_dummies( df_with_dummies, columns = ['PRAEGENDE_JUGENDJAHRE_DIRECTION'] ,drop_first=True)
df_with_dummies['CAMEO_INTL_2015'].value_counts(dropna=False)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
# convert the type of CAMEO_INTL_2015 from int to integer
#df_with_dummies['CAMEO_INTL_2015'] = df_with_dummies['CAMEO_INTL_2015'].astype(int)
#initialize columns
def get_life_stage(number):
if number == '-1' or number == 'XX':
return np.nan
return int(number) % 10
def get_wealth(number):
if number == '-1' or number == 'XX':
return np.nan
number = int(number) //10
return number % 10
df_with_dummies['CAMEO_INTL_2015_WEALTH'] = df_with_dummies['CAMEO_INTL_2015'].apply(get_wealth)
df_with_dummies['CAMEO_INTL_2015_LIFE_STAGE'] = df_with_dummies['CAMEO_INTL_2015'].apply(get_life_stage)
print(df_with_dummies[['CAMEO_INTL_2015', 'CAMEO_INTL_2015_WEALTH', 'CAMEO_INTL_2015_LIFE_STAGE']].head(10).T)
df_with_dummies.drop('CAMEO_INTL_2015', axis=1, inplace=True)
# drop the remaining mixed categories
mixed_features_df = features_info_df.loc[missing_data_le_2.columns][['columns','type']].query('type == "mixed"')
columns = set(mixed_features_df['columns'].tolist())
columns = columns - set(['CAMEO_INTL_2015', 'PRAEGENDE_JUGENDJAHRE'])
pprint(f'columns that will be dropped: {columns}')
df_with_dummies.drop(columns, axis=1, inplace=True)
# check if columns still there
columns in set(df_with_dummies.columns)
df_with_dummies.shape
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
features = feat_info[['attribute','type']]
columns = features['attribute'].tolist()
dict_of_remaining_cols = {}
for col in columns:
if col in df_with_dummies or df_with_dummies.columns.str.startswith(col).any():
df_columns = df_with_dummies.filter(regex=f'{col}.*').columns.tolist()
dict_of_remaining_cols[col] = {
'category' :features[features['attribute'] == col ].iloc[0][1],
'columns': df_columns
}
pprint(f'size of the featires {df_with_dummies.shape[1]}')
print('-'*50)
pprint(dict_of_remaining_cols)
pprint(dict_of_remaining_cols.keys())
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
# remove the columns that has been agreed on in section 1.1.2 if they still exist
# GEBURTSJAHR, TITEL_KZ, KK_KUNDENTYP, KBA05_BAUMAX, ALTER_HH but before check if they are ordinal or interval
cols = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','KK_KUNDENTYP','KBA05_BAUMAX','ALTER_HH']
for c in cols:
if c in dict_of_remaining_cols.keys() and dict_of_remaining_cols[c]['category']== 'categorical':
df_with_dummies.drop(dict_of_remaining_cols[c]['columns'], axis=1, inplace=True)
print(f'dropping: {dict_of_remaining_cols[c]["columns"]}')
df_with_dummies.shape
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
# convert string list to related list of numerics or strings based
import math
def convert(string_list):
missing_values_dict = {}
conv = lambda x: x[1:-1].split(',')
res = conv(string_list)
for item in res:
if item.replace('-','').isnumeric():
missing_values_dict[int(item)] = np.nan
if item.isalpha():
missing_values_dict[str(item)] = np.nan
return missing_values_dict
# related to extract life_stage feature from CAMEO_INTL_2015
def get_life_stage(number):
if number == '-1' or number == 'XX' or math.isnan(float(number)):
return np.nan
return int(number) % 10
# related to extract wealth feature from CAMEO_INTL_2015
def get_wealth(number):
if number == '-1' or number == 'XX' or math.isnan(float(number)):
return np.nan
number = int(number) //10
return number % 10
# extract missing features values from feature_info and construct a dictionary from the values
def get_missing_features_dict_from_features_info(features_info_df):
missing_values = features_info_df[['attribute','missing_or_unknown']].copy()
missing_values = missing_values.query('missing_or_unknown !="[]"')
missing_values['missing_or_unknown'] = missing_values['missing_or_unknown'].apply(convert)
missing_dict = {x[0]: x[1] for x in missing_values.itertuples(index=False)}
return missing_dict
def create_binary_multi_level_features_list(data, features_info_df):
bin_list = []
multi_level_list = []
available_features = []
cat_features = features_info_df[features_info_df['type'] == 'categorical']['attribute'].tolist()
for f in cat_features:
if f in data:
available_features.append(f)
cat_variable = data[available_features]
for t in available_features:
if len(cat_variable[t].value_counts()) == 2 and (
set(cat_variable[t]) & set([0, 1]) == set([0, 1]) or
set(cat_variable[t]) & set([0.0, 1.0]) == set([0.0, 1.0])
):
bin_list.append(t)
else:
multi_level_list.append(t)
return bin_list, multi_level_list
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
available_features = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
missing_features_dict = get_missing_features_dict_from_features_info(available_features)
# Put in code here to execute all main cleaning steps:
# convert missing value codes into NaNs, ...
for key,value in missing_features_dict.items():
df[key].replace(value, inplace=True)
# remove selected columns and rows, ...
#remove columns
columns_to_be_dropped = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','KK_KUNDENTYP','KBA05_BAUMAX','ALTER_HH',
'LP_LEBENSPHASE_GROB', 'PLZ8_BAUMAX','LP_LEBENSPHASE_FEIN', 'WOHNLAGE']
df.drop(columns_to_be_dropped, axis=1, inplace=True)
#drop every row has more that 2 NaNs
df = df[df.isnull().sum(axis=1) < 2].reset_index(drop=True)
# get binary/ multilevel features lists
binary_features_list, multilevel_features_list = create_binary_multi_level_features_list(df, available_features)
#encode features for binary_features_list
df= pd.get_dummies( df, columns = binary_features_list ,drop_first=True)
# drop multi-level
for col in multi_level_list:
df.drop(col, axis=1, inplace=True)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
df['CAMEO_INTL_2015_WEALTH'] = df['CAMEO_INTL_2015'].apply(get_wealth)
df['CAMEO_INTL_2015_LIFE_STAGE'] = df['CAMEO_INTL_2015'].apply(get_life_stage)
df.drop('CAMEO_INTL_2015', axis=1, inplace=True)
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
first_var_dict = {
-1:{'period': np.nan, 'direction': np.nan},
0:{'period': np.nan, 'direction': np.nan},
1: {'period': 40, 'direction': 'EW'},
2: {'period': 40, 'direction': 'EW'},
3: {'period': 50, 'direction': 'EW'},
4: {'period': 50, 'direction': 'EW'},
5: {'period': 60, 'direction': 'EW'},
6: {'period': 60, 'direction': 'W'},
7: {'period': 60, 'direction': 'E'},
8: {'period': 70, 'direction': 'EW'},
9: {'period': 70, 'direction': 'EW'},
10: {'period': 80, 'direction': 'W'},
11: {'period': 80, 'direction': 'W'},
12: {'period': 80, 'direction': 'E'},
13: {'period': 80, 'direction': 'E'},
14: {'period': 90, 'direction': 'EW'},
15: {'period': 90, 'direction': 'EW'}
}
#initialize two columns
df['PRAEGENDE_JUGENDJAHRE_PERIOD']= 0
df['PRAEGENDE_JUGENDJAHRE_DIRECTION'] = 'x'
for key, values in first_var_dict.items():
row_indexes = df[df['PRAEGENDE_JUGENDJAHRE'] == key].index
df.loc[row_indexes,'PRAEGENDE_JUGENDJAHRE_PERIOD']= values['period']
df.loc[row_indexes,'PRAEGENDE_JUGENDJAHRE_DIRECTION']= values['direction']
# check missing
print(f'missing values for [PRAEGENDE_JUGENDJAHRE_PERIOD]: ', df[df['PRAEGENDE_JUGENDJAHRE_PERIOD'] == 0].shape[0])
print('missing values for [PRAEGENDE_JUGENDJAHRE_DIRECTION]: ', df[df['PRAEGENDE_JUGENDJAHRE_DIRECTION'] == 'x'].shape[0])
# drop the original column
df.drop(['PRAEGENDE_JUGENDJAHRE'], axis=1, inplace=True)
#create dummy from direction
df = pd.get_dummies( df, columns = ['PRAEGENDE_JUGENDJAHRE_DIRECTION'] ,drop_first=True)
# final validation
#check if columns still there column to be dropped
mixed_features_df = available_features.query('type == "mixed"')[['attribute','type']]
columns = set(mixed_features_df['attribute'].tolist())
columns = columns - set(columns_to_be_dropped) - set(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'])
df.drop(columns, axis=1, inplace=True)
columns in set(df.columns)
features = available_features[['attribute','type']]
columns = features['attribute'].tolist()
dict_of_remaining_cols = {}
for col in columns:
if col in df or df.columns.str.startswith(col).any():
df_columns = df.filter(regex=f'{col}.*').columns.tolist()
dict_of_remaining_cols[col] = {
'category' :features[features['attribute'] == col ].iloc[0][1],
'columns': df_columns
}
for c in columns_to_be_dropped:
if c in dict_of_remaining_cols.keys() and dict_of_remaining_cols[c]['category']== 'categorical':
df.drop(dict_of_remaining_cols[c]['columns'], axis=1, inplace=True)
#df['GEBAEUDETYP_5.0'].value_counts()
# drop the below column because
#0.0 697108
#1.0 1
#Name: GEBAEUDETYP_5.0, dtype: int64
# and this column doesnt exist after cleanup the clustomer data
if 'GEBAEUDETYP_5.0' in df.columns:
df.drop(['GEBAEUDETYP_5.0'], axis=1, inplace=True)
# Return the cleaned dataframe.
return df
clean_df = clean_data(pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';'))
clean_df.shape
set(clean_df.columns.tolist()) - set(df_with_dummies.columns.tolist())
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
clean_df = clean_data(pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';'))
#clean_df.dropna(axis=0, how='any', inplace=True)
fill_NaN = Imputer(missing_values=np.nan, strategy='mean', axis=1)
imputed_df = pd.DataFrame(fill_NaN.fit_transform(clean_df))
imputed_df.columns = clean_df.columns
imputed_df.index = clean_df.index
imputed_df.head()
# Apply feature scaling to the general population demographics data.
normalizer = StandardScaler()
imputed_df[imputed_df.columns] = normalizer.fit_transform(imputed_df[imputed_df.columns].as_matrix())
imputed_df.head()
all features has been scaled but before scalling filled the NaNs with the mean value
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.# pca
def do_pca(n_components, data):
pca = PCA(n_components)
X_pca = pca.fit_transform(data)
return pca, X_pca
#plot relation between components and the ammount of retained information per component
def scree_plot(pca):
fig, ax = plt.subplots(figsize=(25,7))
cumsum = np.cumsum(pca.explained_variance_ratio_)
plt.plot(np.apply_along_axis(lambda x: x*100, 0, cumsum))
ax.grid()
plt.xticks(range(0, pca.explained_variance_.shape[0]+10, 10))
plt.yticks(range(0, 100, 10))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
# explain variance per component
def explain_variance(pca):
fig, ax = plt.subplots(figsize=(25,7))
ax.grid()
cumsum = np.cumsum(pca.explained_variance_ratio_)
plt.plot(pca.explained_variance_ratio_, label='variance')
#plt.plot(cumsum, label='retained information')
plt.xticks(range(0, pca.explained_variance_.shape[0]+10, 10))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
#plt.legend()
def pca_results(full_dataset, pca):
dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_, 4), columns = full_dataset.keys())
components.index = dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
# Return a concatenated DataFrame
return pd.concat([variance_ratios, components], axis = 1)
def print_weight_vs_feature(pca, dataset_keys):
dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
components = pd.DataFrame(np.round(pca.components_, 4), columns = dataset_keys)
# Create a bar plot visualization
fig, ax = plt.subplots(figsize = (14,8))
# Plot the feature weights as a function of the components
components.plot(ax = ax, kind = 'bar');
ax.set_ylabel("Feature Weights")
#ax.set_xticklabels(dimensions, rotation=90)
# Display the explained variance ratios
for i, ev in enumerate(pca.explained_variance_ratio_):
ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n %.4f"%(ev))
# Apply PCA to the data.
pca_full, X_pca_full = do_pca(imputed_df.shape[1], imputed_df)
X_pca_full.shape
# Investigate the variance accounted for by each principal component.
scree_plot(pca_full)
explain_variance(pca_full)
# Re-apply PCA to the data while selecting for number of components to retain.
pca_30, X_pca_30 = do_pca(30, imputed_df)
scree_plot(pca_30)
explain_variance(pca_30)
pca_15, X_pca_15 = do_pca(15, imputed_df)
scree_plot(pca_15)
explain_variance(pca_15)
from IPython.core.display import HTML
display(HTML(pca_results(imputed_df, pca_15).T.to_html()))
The way i see the accumelated retained information after 50 principle component start to vanish, as at 50 it explains almost 95% of the entire features.
im going to use 20 compenents as it explains a a almost 70% of the variability in the dataset which i beleive is good number and it retains high ratio of information. i choose not to follow the elbow role which is around the 5th pc as it explains 50% of the variability in the dataset which is quite low.
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
def pc_weight_per_feature(pca, dataset_df, what=0):
indecies = [f'{i}' for i in range(1, 16)]
df = pd.DataFrame(pca.components_, columns=dataset_df.columns, index=indecies)
df.index.name = 'level'
if what == 0:
return df
else:
s = df.iloc[what-1].sort_values(ascending=False)
return s
def convert_to_ordered_dict(d):
from collections import OrderedDict
return OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))
pc_weights = pc_weight_per_feature(pca_15, imputed_df)
pc_weights.head(3)
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
pc1_weights = pc_weight_per_feature(pca_15, imputed_df, 1)
pc1_top_5 = pc1_weights.keys()[1:6].tolist()
pc1_lower_5 = pc1_weights.keys()[-6:-1].tolist()
#convert_to_ordered_dict(pc_weights)
print(pc1_weights)
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pc2_weights = pc_weight_per_feature(pca_15, imputed_df, 2)
pc2_top_5 = pc2_weights.keys()[1:6].tolist()
pc2_lower_5 = pc2_weights.keys()[-6:-1].tolist()
#convert_to_ordered_dict(pc_weights)
pc2_weights
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pc3_weights = pc_weight_per_feature(pca_15, imputed_df, 3)
pc3_top_5 = pc3_weights.keys()[1:6].tolist()
pc3_lower_5 = pc3_weights.keys()[-6:-1].tolist()
#convert_to_ordered_dict(pc_weights)
pc3_weights
pc30_weights = pc_weight_per_feature(pca_15, imputed_df, 15)
pc3_top_5 = pc30_weights.keys()[1:6].tolist()
pc3_lower_5 = pc30_weights.keys()[-6:-1].tolist()
#convert_to_ordered_dict(pc_weights)
print(pc3_weights)
print('-'*22, 'TOP 5', '-'*22)
print(f'pc1: {pc1_top_5}')
print(f'pc2: {pc2_top_5}')
print(f'pc3: {pc3_top_5}')
print('-'*22, 'LOW 5', '-'*22)
print(f'pc1: {pc1_lower_5}')
print(f'pc2: {pc2_lower_5}')
print(f'pc3: {pc3_lower_5}')
based on the privious results for the first 3 pc's we could say
for every pc level their is different features that contributes more than other in creating the biggest variance or explains the most variance. the variance is not affected by the sign as the sign represents direction not magnitude. so the main contributers are the top 5 features and the lower 5 features.
top 5 and lower 5 is highly correlated as they have been loaded in the SAME Principal Component (Eigenvector). which means that an increase in one the remaining ones tend to increase as well.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.def get_kmeans_score(data, center):
kmeans = KMeans(n_clusters=center, random_state=42)
model = kmeans.fit(data)
score = np.abs(model.score(data))
return model, score
# Over a number of different cluster counts...
# run k-means clustering on the data and...
# compute the average within-cluster distances.
scores = []
models = []
centers = list(range(1,27, 3))
for center in centers:
model, score = get_kmeans_score(X_pca_15, center)
labels = model.predict(X_pca_15)
scores.append(score)
models.append(model)
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plt.plot(centers, scores, linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans = KMeans(n_clusters=15)
model = kmeans.fit(X_pca_15)
predictions = model.predict(X_pca_15)
from the above plot, its not clear where is the cut-off point as the SSE continues to minimize smoothly, but we can see also that around 15 the SSE decrease almost negligible, which lead me to choose 15 clusters
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
print(customers.shape)
customers.head(3)
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
clean_customers_df =clean_data(customers)
print(clean_customers_df.shape)
clean_customers_df.head(3)
clean_customers_df[clean_customers_df.columns].shape
#remove NaNs
fill_NaN = Imputer(missing_values=np.nan, strategy='mean', axis=1)
df = pd.DataFrame(fill_NaN.fit_transform(clean_customers_df))
df.columns = clean_customers_df.columns
df.index = clean_customers_df.index
df.head()
df[df.columns] = normalizer.transform(df[df.columns].as_matrix())
#transform the customers data using pca object
X_customer_pca = pca_15.transform(df)
#predict clustering using the kmeans object
predict_customers = model.predict(X_customer_pca)
print(df.shape)
df.head()
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
general_prop = []
customers_prop = []
x = [i+1 for i in range(15)]
for i in range(15):
general_prop.append((predictions == i).sum()/len(predictions))
customers_prop.append((predict_customers == i).sum()/len(predict_customers))
fig, ax = plt.subplots()
df_general = pd.DataFrame({'cluster' : x, 'general' : general_prop, 'customers':customers_prop})
df_general.plot(x='cluster', y = ['general', 'customers'], kind='bar', figsize=(20,10), ax=ax)
plt.ylabel('proportion of persons in each cluster')
ax.grid()
plt.show()
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
# the 10th cluster is overrepresented
data1_10 = normalizer.inverse_transform(pca_15.inverse_transform(X_customer_pca[np.where(predict_customers==9)])).round()
df = pd.DataFrame(data=data1_10,
index=np.array(range(0, data1_10.shape[0])),
columns=df.columns)
df.head(20)
#general part
data_2_10 = normalizer.inverse_transform(pca_15.inverse_transform(X_pca_15[np.where(predictions==9)])).round()
df = pd.DataFrame(data=data_2_10,
index=np.array(range(0, data_2_10.shape[0])),
columns=df.columns)
df.head(20)
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
# cluster 8
data_1_8 = normalizer.inverse_transform(pca_15.inverse_transform(X_customer_pca[np.where(predict_customers==7)])).round()
df = pd.DataFrame(data=data_1_8,
index=np.array(range(0, data_1_8.shape[0])),
columns=df.columns)
df.head(20)
#general
data_2_8 = normalizer.inverse_transform(pca_15.inverse_transform(X_pca_15[np.where(predictions==7)])).round()
df = pd.DataFrame(data=data_2_8,
index=np.array(range(0, data_2_8.shape[0])),
columns=df.columns)
df.head(20)
cust_df = pd.DataFrame(X_customer_pca, columns=np.arange(1, 16))
cust_df['cluster'] = predict_customers
cust_df.describe()
g = sns.pairplot(cust_df,
vars = np.arange(1, 16),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
(Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?)
cluster 4, 10 are overrepresented in the customer data compared to the general population, while clusters 8, 15 is the clusters that is being underpresented based on customer data.
i think we could safely assume the the people in cluster 4, 9 are the most interesting people from customer base prespective, as for the features role extraction form PCA_15 that Personality typology, affectes positively, on the other hand it could be that the traget customers are likely to be the ones that belongs to those clusters from the general population
also what we could see from the pairplot that the seperation of clustes it clear up to the 4th component, and more uniformally distributed.
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.